#!/usr/bin/env bash
set -eo pipefail

declare -r SCRIPT_DIR=$(cd $(dirname $0) >/dev/null 2>&1 && pwd)
source ${SCRIPT_DIR}/common.sh

declare -r tag=$1 container_name=$2 data=$3 config=$4 logs=$5

declare -ra docker_run_influxd=(
    docker run -i -d
    --name=${container_name}
    -u $(id -u):influxdb
    -p 8086:8086
    -v ${data}:/var/lib/influxdb2
    -v ${config}:/etc/influxdb2
    -e DOCKER_INFLUXDB_INIT_MODE=setup
    -e DOCKER_INFLUXDB_INIT_USERNAME=${TEST_USER}
    -e DOCKER_INFLUXDB_INIT_PASSWORD=${TEST_PASSWORD}
    -e DOCKER_INFLUXDB_INIT_ORG=${TEST_ORG}
    -e DOCKER_INFLUXDB_INIT_BUCKET=${TEST_BUCKET}
    -e DOCKER_INFLUXDB_INIT_RETENTION=${TEST_RETENTION_SECONDS}s
    influxdb:${tag} influxd run
)

# Boot the container
log_msg Booting 2.x container in setup mode
if ! ${docker_run_influxd[@]} > /dev/null; then
    log_msg Error: Failed to launch container
    exit 1
fi
wait_container_ready

# Get the auth token generated by setup.
declare -r auth_token=$(extract_token ${container_name})

log_msg Checking bucket RP
declare rp=$(curl -s -H "Authorization: Token ${auth_token}" "localhost:8086/api/v2/buckets?name=${TEST_BUCKET}" | jq -r .buckets[].retentionRules[].everySeconds)

if [[ ${rp} != ${TEST_RETENTION_SECONDS} ]]; then
    log_msg Error: Bad bucket RP post-setup
    echo ${rp}
    exit 1
fi
